package com.stillalive.mq.mqserver;

import com.stillalive.mq.common.*;
import com.stillalive.mq.common.parameterPassing.*;
import com.stillalive.mq.mqserver.core.BasicProperties;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BrokerServer {
    private ServerSocket serverSocket = null;
    // 考虑一个BrokerServer上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    // 使用这个哈希表表示当前的所有会话（哪些客户端正在与服务器进行通信）
    // 此处的key是channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<String, Socket>();
    // 引入线程池来处理客户端的请求
    private ExecutorService executorService = null;
    // 引入一个boolean变量控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动！");
        executorService = Executors.newCachedThreadPool();
        try {
            while(runnable){
                Socket clientSocket = serverSocket.accept();
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器关闭！");
        }
    }
    //
    public void stop() {
        runnable = false;
        // 把线程池中的任务都放弃，线程都销毁
        executorService.shutdownNow();
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 处理一个客户端的连接
    private void processConnection(Socket clientSocket) {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            // 这里需要按照特定格式来读取并解析，此时需要用到DataInputStream和DataOutputStream
            // 和之前一样的，这里文件读取结束会抛出一个EOF异常，这个异常会被后面catch捕获到
            try(DataInputStream dataInputStream = new DataInputStream(inputStream);
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream)){
                while(true){
                    // 读取请求并解析
                    Request request = readRequest(dataInputStream);
                    // 根据请求计算响应
                    Response response = process(request, clientSocket);
                    // 把相应写回给客户端
                    writeResponse(dataOutputStream, response);
                }
            }catch(EOFException | SocketException | ClassNotFoundException | MqException e){
                // 这里借助这个异常来结束循环
                System.out.println("[BrokerServer] connection关闭！客户端地址：" + clientSocket.getInetAddress().toString()
                        + ":" + clientSocket.getPort());
            }
        }catch (IOException e){
            System.out.println("[BrokerServer] connection出现异常！");
            e.printStackTrace();
        }finally {
            try{
                clientSocket.close();
                clearCloseSession(clientSocket);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if(n != request.getLength()){
            throw new IOException("读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 初步解析request中的payload
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId()
        + ", type:" + request.getType() + ", length:" + request.getLength());
        boolean ok = true;
        // 根据type的值，来进一步区分接下来做什么
        if(request.getType() == 0x1){
            // 创建channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建channel完成！channelId=" + basicArguments.getChannelId());
        }else if(request.getType() == 0x2){
            // 销毁channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁channel完成！channelId=" + basicArguments.getChannelId());
        }else if(request.getType() == 0x3){
            // 创建交换机，payload就是ExchangeDeclareArguments对象了
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        }else if (request.getType() == 0x4) {
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(),
                    arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete((arguments.getQueueName()));
        } else if (request.getType() == 0x7) {
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        }else if(request.getType() == 0xa) {
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        // 这个回调函数，把服务器收到的消息直接推回对应的客户端
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            // 根据channelId找到socket对象
                            Socket clientSocket = sessions.get(consumerTag);
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭！");
                            }
                            // 构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(arguments.getChannelId());
                            subScribeReturns.setRid(""); // 这里只有相应没有请求，不需要去对应，暂时不需要rid
                            subScribeReturns.setBasicProperties(basicProperties);
                            subScribeReturns.setOk(true);
                            subScribeReturns.setConsumerTag(consumerTag);
                            subScribeReturns.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);
                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            // 数据写回给客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            // 调用basicAck来确认信息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        }else {
            // 当前的type是非法的
            throw new MqException("[BrokerServer] 未知的type！type=" + request.getType());
        }
        // 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid=" +  basicReturns.getRid() + ", channelId=" + basicReturns.getChannelId()
               + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        // 这里的刷新缓冲区可以保证数据快速的写入到网卡中
        dataOutputStream.flush();
    }
    private void clearCloseSession(Socket clientSocket) {
        List<String> toDeleteChannelId = new ArrayList<>();
        for(Map.Entry<String, Socket> entry : sessions.entrySet()){
            if(entry.getValue() == clientSocket){
                // 集合类不能一边遍历一边删除，会导致集合内部结构错乱
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for(String channelId : toDeleteChannelId){
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理session完成！");
    }
}
